const https = require('https')
const {
  mysql
} = require('../qcloud')

module.exports = async (ctx) => {

  const {
    avatarUrl,
    city,
    country,
    gender,
    language,
    nickName,
    openid,
    province
  } = ctx.request.body;

  if (openid) {
    const findRes = await mysql('users').select().where('openid', openid)

    if (findRes.length) {
      ctx.state = {
        code: 0,
        data: {
          msg: '用户已添加'
        }
      }
      return
    }

    try {
      await mysql('users').insert({
        avatarUrl,
        city,
        country,
        gender,
        language,
        nickName,
        openid,
        province
      })

      ctx.state.data = {
        code: 1,
        msg: '添加用户成功'
      }
    } catch (e) {
      // 捕捉错误
      ctx.state = {
        code: -1,
        data: {
          msg: '新增用户失败:' + e.sqlMessage
        }
      }
    }
  }

}
